package chapter1.socket.task.task4;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/*
4：假设有个Socket服务器，提供查询气温，风力，pm2.5,湿度等气象服务，请设计服务端和客户端实现，提供退出功能，并使用多线程防止服务端堵塞。
客户端选择要查询的类型，是气温，还是其他，服务端返回相应的值，并加上当前的日期（用yyyy-MM-dd hh:mm:ss格式），
服务端通过多线程的方式提高性能,客户端发送和接收统一采用字符串格式用多线程提高响应速度
 */
public class Client {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Socket socket = null;
        PrintWriter out = null;
        try {
            socket = new Socket("127.0.0.1", 1800);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            Read read = new Read();
            read.setBufferedReader(in);
            new Thread(read).start();
            System.out.print("客户端输入要查询的类型：");
            while (true) {
                String s = input.nextLine();   
                if (s.equals("quit")) {
                    socket.close();
                    System.exit(0);
                }
                out.println(s);
            }

        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


class Read implements Runnable {
    BufferedReader in;

    public void setBufferedReader(BufferedReader in) {
        this.in = in;
    }

    @Override
    public void run() {
        while (true) {
            try {
                String s = in.readLine();  
                System.out.println("服务端返回：" + s);
               System.out.print("客户端输入要查询的类型：");
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

